"""
    Author:
    Date: 2018-11-27

    SMS辅助函数。
"""

from yunpian_python_sdk.model import constant as YC
from yunpian_python_sdk.ypclient import YunpianClient

from utils.log import Log


def send_sms_code(mobile, code, apikey):
    """ 给指定的手机发送验证码 """
    # 初始化client,apikey作为所有请求的默认值
    client = YunpianClient(apikey)
    param = {
        YC.MOBILE: mobile,
        YC.TEXT: f"【阿拉贡】您的验证码是{code}，五分钟内有效。如非本人操作，请忽略本短信",
    }
    r = client.sms().single_send(param)

    # 获取返回结果:
    # 返回码:r.code(),
    # 返回码描述:r.msg(),
    # API结果:r.data(),
    # 其他说明:r.detail(),
    # 调用异常:r.exception()
    if r.code() != 0:
        Log.error(f'Send sms code failed: {r.msg()}, mobile={mobile}')
        return False
    return True


def send_sms_message(mobile, text, apikey):
    """ 给指定的手机发送消息 """
    # 初始化client,apikey作为所有请求的默认值
    client = YunpianClient(apikey)
    param = {
        YC.MOBILE: mobile,
        YC.TEXT: text,
    }
    r = client.sms().single_send(param)

    # 获取返回结果:
    # 返回码:r.code(),
    # 返回码描述:r.msg(),
    # API结果:r.data(),
    # 其他说明:r.detail(),
    # 调用异常:r.exception()
    if r.code() != 0:
        Log.error(f'Send sms code failed: ${r.msg()}, mobile=${mobile}')
        return False
    return True


# ------------------------------------------------------------------------------
if __name__ == '__main__':
    print('ok')
